const pageHelper = require('../../../../../helper/page_helper.js');
const cloudHelper = require('../../../../../helper/cloud_helper.js');
const validate = require('../../../../../helper/validate.js');
const ProjectBiz = require('../../../biz/project_biz.js');
const projectSetting = require('../../../public/project_setting.js');
const setting = require('../../../../../setting/setting.js');
const PassportBiz = require('../../../../../comm/biz/passport_biz.js');
const RequestBiz = require('../../../../../comm/biz/request_biz.js');

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		isLoad: false,
		isEdit: true,
		userRegCheck: projectSetting.USER_REG_CHECK,
		mobileCheck: setting.MOBILE_CHECK
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function (options) {
		ProjectBiz.initPage(this);
		await this._loadDetail();
	},

	_loadDetail: async function (e) {
		let user = PassportBiz.getToken();
		this.setData({
			formName: user.name,
			formPic: user.pic,
			formScore: user.score,
			formRankName: user.rankName,
			isLoad: true,
			openid: user.openid,
		});
		RequestBiz.request("/api/ysjl/user/userInfo", {id: user.id}).then(res => {
			if (res.data.ret == 0) {
				this.setData({
					formScore: res.data.data.score,
					formRankName: res.data.data.rankName,
				});
			}
		});

	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: async function () {
		await this._loadDetail();
		wx.stopPullDownRefresh();
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	bindGetPhoneNumber: async function (e) {
		await PassportBiz.getPhone(e, this);
	},

	bindPicTap: function (e) {  
		this.setData({
			formPic: e.detail.avatarUrl
		})
	},

	bindSubmitTap: async function (e) {
		let data = this.data;
		// 数据校验 
		data = validate.check(data, projectSetting.USER_CHECK_FORM, this);
		if (!data) return;

		let forms = this.selectComponent("#cmpt-form").getForms(true);
		if (!forms) return;
		data.forms = forms;

		wx.showLoading({ title: '头像上传中' });
		let picReq;
    if (data.pic.includes('http://tmp')) {
			picReq = await RequestBiz.uploadFile('/api/ysjl/user/uploadPic', data.pic, {});
		}
		wx.hideLoading();
		let req = RequestBiz.request('/api/ysjl/user/register', {
			name: data.name,
			pic: picReq ? JSON.parse(picReq.data).data : null,
			openid: this.data.openid
		});
		req.then(res => {
			let retData = res.data;
			if (retData.ret == 0) {
				PassportBiz.setToken(retData.data);
				wx.reLaunch({ url: '../index/my_index' });
			}
		})
	}
})